import React from "react";
import { Button, Form, Input, Space, Table, Upload, Modal, InputNumber, Switch, DatePicker, message } from "antd";
import { PlusOutlined, DeleteOutlined, EditOutlined, UploadOutlined } from "@ant-design/icons";
import {
  DetectionPointNewItem,
  getDetectionPointNewList,
  createDetectionPointNew,
  updateDetectionPointNew,
  deleteDetectionPointNew,
} from "../../api/gis";
import { useEffect, useState } from "react";
import { useRef } from "react";
import dayjs from "dayjs";
import DetectionPointBatchUploadModal from "./DetectionPointBatchUploadModal";

interface Props {
  planetId: number;
  inspectionAreaId: number;
  reloadFlag?: number;
  onChanged?: () => void; // 通知父组件刷新树
}

const DetectionPointPanel: React.FC<Props> = ({
  planetId,
  inspectionAreaId,
  reloadFlag = 0,
  onChanged,
}) => {
  const [data, setData] = useState<DetectionPointNewItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<DetectionPointNewItem | null>(null);
  const [form] = Form.useForm();
  
  // 批量上传弹窗状态
  const [batchUploadModalVisible, setBatchUploadModalVisible] = useState(false);

  // 表格容器与固定高度
  const tableContainerRef = useRef<HTMLDivElement | null>(null);
  const [tableScrollY, setTableScrollY] = useState<number>(0);

  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      // 参照地名管理的计算方式
      const pageHeight = window.innerHeight;
      const breadcrumbHeight = 48;
      const tabsHeaderHeight = 46;
      const filterFormHeight = 0;
      const actionButtonsHeight = 56;
      const padding = 242; // 与地名管理保持一致

      const availableHeight =
        pageHeight - breadcrumbHeight - tabsHeaderHeight - filterFormHeight - actionButtonsHeight - padding;
      const tableHeaderHeight = 39;
      const scrollHeight = Math.max(availableHeight - tableHeaderHeight, 100);

      setTableScrollY(scrollHeight);

      const tableBody = tableContainerRef.current.querySelector(".ant-table-body") as HTMLElement | null;
      if (tableBody) {
        tableBody.style.height = scrollHeight + "px";
        tableBody.style.maxHeight = scrollHeight + "px";
      }
    }
  };

  const fetchList = async () => {
    if (!inspectionAreaId) return;
    setLoading(true);
    try {
      const res = await getDetectionPointNewList({ inspection_area_id: inspectionAreaId });
      if (res.code === 200) {
        setData(res.data.list);
        setTotal(res.data.count);
        setCurrent(res.data.page);
        setPageSize(res.data.page_size);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [planetId, inspectionAreaId, reloadFlag]);

  useEffect(() => {
    const timer = setTimeout(() => {
      calculateTableScrollHeight();
    }, 100);
    const onResize = () => calculateTableScrollHeight();
    window.addEventListener("resize", onResize);
    return () => {
      clearTimeout(timer);
      window.removeEventListener("resize", onResize);
    };
  }, []);

  const handleCreate = () => {
    setEditing(null);
    form.resetFields();
    setModalOpen(true);
  };

  const handleEdit = (record: DetectionPointNewItem) => {
    setEditing(record);
    form.setFieldsValue({
      detection_name: record.detection_name,
      detection_num: record.detection_num,
      detection_time_range: [dayjs(record.detection_strat_time), dayjs(record.detection_end_time)],
      center_latitude: record.center_latitude,
      center_longitude: record.center_longitude,
      is_special: record.is_special === 1,
    });
    setModalOpen(true);
  };

  const handleDelete = (record: DetectionPointNewItem) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除探测点 "${record.detection_name}" 吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const res = await deleteDetectionPointNew({
          ids: [record.id],
        });
        if (res.code === 200) {
          message.success("删除成功");
          fetchList();
          onChanged?.();
        } else {
          message.error(res.msg || "删除失败");
        }
      },
    });
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) return;
    Modal.confirm({
      title: "确认批量删除",
      content: `确定要删除选中的 ${selectedRowKeys.length} 个探测点吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        const res = await deleteDetectionPointNew({
          ids: selectedRowKeys.map(Number),
        });
        if (res.code === 200) {
          message.success("批量删除成功");
          setSelectedRowKeys([]);
          fetchList();
          onChanged?.();
        } else {
          message.error(res.msg || "批量删除失败");
        }
      },
    });
  };

  const handleSave = async () => {
    const values = await form.validateFields();
    const [startTime, endTime] = values.detection_time_range || [];
    const params = {
      planet_id: planetId,
      inspection_area_id: inspectionAreaId,
      detection_name: values.detection_name,
      detection_num: values.detection_num,
      detection_strat_time: startTime?.format("YYYY-MM-DD HH:mm:ss"),
      detection_end_time: endTime?.format("YYYY-MM-DD HH:mm:ss"),
      center_latitude: values.center_latitude,
      center_longitude: values.center_longitude,
      is_special: values.is_special ? 1 : 0,
    };
    if (editing) {
      const res = await updateDetectionPointNew({ detection_point_id: editing.id, ...params });
      if (res.code === 200) {
        message.success("修改成功");
        setModalOpen(false);
        fetchList();
        onChanged?.();
      } else {
        message.error(res.msg || "修改失败");
      }
    } else {
      const res = await createDetectionPointNew(params);
      if (res.code === 200) {
        message.success("创建成功");
        setModalOpen(false);
        fetchList();
        onChanged?.();
      } else {
        message.error(res.msg || "创建失败");
      }
    }
  };

  // 批量上传成功回调
  const handleBatchUploadSuccess = () => {
    fetchList();
    onChanged?.();
  };

  const columns = [
    { title: "ID", dataIndex: "id", key: "id", width: 80, ellipsis: true },
    { title: "探测点编号", dataIndex: "detection_num", key: "detection_num", width: 120, ellipsis: true },
    { title: "开始时间", dataIndex: "detection_strat_time", key: "detection_strat_time", width: 180, ellipsis: true },
    { title: "结束时间", dataIndex: "detection_end_time", key: "detection_end_time", width: 180, ellipsis: true },
    { title: "纬度", dataIndex: "center_latitude", key: "center_latitude", width: 100, ellipsis: true },
    { title: "经度", dataIndex: "center_longitude", key: "center_longitude", width: 100, ellipsis: true },
    {
      title: "是否特殊点",
      dataIndex: "is_special",
      key: "is_special",
      width: 100,
      ellipsis: true,
      render: (v: number) => (v === 1 ? "是" : "否"),
    },
    { title: "创建时间", dataIndex: "create_time", key: "create_time", width: 180, ellipsis: true },
    {
      title: "操作",
      key: "action",
      width: 200,
      fixed: "right" as const,
      align: "center" as const,
      render: (_: any, record: DetectionPointNewItem) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <>
      <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
        {/* <div style={{ flexShrink: 0 }}>
          <Form layout="inline" className="filter-form" labelCol={{ style: { width: 120 } }}>
            <Form.Item label="探测点名称" style={{ width: 320 }}>
              <Input placeholder="请输入探测点名称搜索" />
            </Form.Item>
            <Form.Item style={{ paddingLeft: 40 }}>
              <Space>
                <Button type="primary">筛选</Button>
                <Button>清除</Button>
              </Space>
            </Form.Item>
          </Form>
        </div> */}

        <div
          style={{
            marginBottom: 16,
            marginTop: 16,
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            flexShrink: 0,
          }}
        >
          <div>
            <Button type="primary" danger onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0}>
              批量删除
            </Button>
          </div>
          <Space>
            <Button 
              icon={<UploadOutlined />} 
              onClick={() => setBatchUploadModalVisible(true)}
            >
              批量导入
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
              新建探测点
            </Button>
          </Space>
        </div>

        <div style={{ flex: 1, overflow: "hidden" }}>
          <div className="pds-table-container" style={{ height: "100%" }} ref={tableContainerRef}>
            <Table
              rowSelection={{ selectedRowKeys, columnWidth: 50, onChange: (keys) => setSelectedRowKeys(keys) }}
              columns={columns}
              dataSource={data}
              rowKey="id"
              loading={loading}
              pagination={{
                current,
                pageSize,
                total,
                showSizeChanger: true,
                pageSizeOptions: ["10", "20", "50"],
                onChange: (p, s) => {
                  setCurrent(p);
                  setPageSize(s!);
                },
                showTotal: (t) => `共 ${t} 条`,
              }}
              scroll={{ y: tableScrollY, x: "max-content" }}
              bordered
              size="small"
            />
          </div>
        </div>
      </div>

      <Modal
        title={editing ? "编辑探测点" : "新建探测点"}
        open={modalOpen}
        onOk={handleSave}
        onCancel={() => setModalOpen(false)}
        width={800}
        okText="保存"
        cancelText="取消"
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <div style={{ display: "flex", gap: 16 }}>
            <div style={{ flex: 1 }}>
              <Form.Item
                name="detection_num"
                label="探测点编号"
                rules={[{ required: true, message: "请输入探测点编号" }]}
              >
                <Input placeholder="请输入探测点编号" />
              </Form.Item>
              <Form.Item
                name="detection_time_range"
                label="探测时间范围"
                rules={[{ required: true, message: "请选择探测时间范围" }]}
              >
                <DatePicker.RangePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  style={{ width: "100%" }}
                />
              </Form.Item>
              <Form.Item name="is_special" label="是否特殊点" valuePropName="checked">
                <Switch />
              </Form.Item>
            </div>
            <div style={{ flex: 1 }}>
              <Form.Item name="center_latitude" label="纬度" rules={[{ required: true, message: "请输入纬度" }]}>
                <InputNumber placeholder="请输入纬度" style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item name="center_longitude" label="经度" rules={[{ required: true, message: "请输入经度" }]}>
                <InputNumber placeholder="请输入经度" style={{ width: "100%" }} />
              </Form.Item>
            </div>
          </div>
        </Form>
      </Modal>

      {/* 批量上传探测点弹窗 */}
      <DetectionPointBatchUploadModal
        visible={batchUploadModalVisible}
        onCancel={() => setBatchUploadModalVisible(false)}
        planetId={planetId}
        inspectionAreaId={inspectionAreaId}
        onSuccess={handleBatchUploadSuccess}
      />
    </>
  );
};

export default DetectionPointPanel;
